import React, { PureComponent } from "react";
import { BackHandler, DeviceEventEmitter, Platform } from "react-native";
import { NavigationActions } from "react-navigation";
import {
  reduxifyNavigator,
  createReactNavigationReduxMiddleware,
  createNavigationReducer,
} from "react-navigation-redux-helpers";
import { connect } from "react-redux";
import { Provider, Toast } from "@ant-design/react-native";
import Loading from "components/Loading";
import { RNReload } from "components/Reload";

import AppRouter from "./routers/index";

export const routerReducer = createNavigationReducer(AppRouter);

export const routerMiddleware = createReactNavigationReduxMiddleware(
  "root",
  state => state.router
);

const App = reduxifyNavigator(AppRouter, "root");

function getActiveRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  if (route.routes) {
    return getActiveRouteName(route);
  }
  return route.routeName;
}

class Router extends PureComponent {
  componentWillMount() {
    BackHandler.addEventListener("hardwareBackPress", this.backHandle);
  }

  componentWillReceiveProps() {
    // const { publicData } = this.props;
    // console.log("Receive isLogin", publicData.isLogin);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.backHandle);
  }

  backHandle = () => {
    const { router, dispatch } = this.props;
    const currentScreen = getActiveRouteName(router);
    // console.log(currentScreen);
    // if (currentScreen === "Welcome") {
    //   NavigationActions.navigate({ routeName: "Home" });
    //   return true;
    // }

    // if (currentScreen !== "Home") {
    //   dispatch(NavigationActions.back());
    //   return true;
    // }
    if (currentScreen === "Home") {
      if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        // 最近2秒内按过back键，可以退出应用。
        if (Platform.OS === "android") {
          RNReload.exitApp();
        } else {
          BackHandler.exitApp();
        }

        return false;
      }
      this.lastBackPressed = Date.now();
      Toast.show("再按一次退出应用", 1);
      return true;
    } else {
      // NoticeUnLogin
      const { publicData } = this.props;
      // console.log(publicData.isLogin);
      if (currentScreen === "Login" && !publicData.isLogin) {
        // dispatch(NavigationActions.back());
        DeviceEventEmitter.emit("NoticeUnLogin");
        // return true;
      }
      dispatch(NavigationActions.back());
      return true;
    }
  };

  render() {
    const { publicData, dispatch, router } = this.props;
    if (publicData.loading) return <Loading />;

    return (
      <Provider>
        <App dispatch={dispatch} state={router} />
        {/* <Modal /> */}
      </Provider>
    );
  }
}

export default connect(stores => ({
  publicData: stores.public,
  router: stores.router,
}))(Router);
